package com.key.w8.http1.factory;

import com.key.w8.http1.entity.HttpRequest;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.FileRegion;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

/**
 * @Author: k8
 * @CreateTime: 2025-04-27
 * @Version: 1.0
 */
public class FormDataBuilder {
    private HttpMethod httpMethod;
    private HttpHeaders httpHeaders;
    private Map<String, List<String>> paras;
    private HttpVersion httpVersion;
    private FormData formData;
    private String uri;
    FormDataBuilder(HttpMethod httpMethod, HttpHeaders httpHeaders, HttpVersion httpVersion, String uri, Map<String, List<String>> paras) {

        this.httpMethod = httpMethod;
        this.httpHeaders = httpHeaders;
        this.httpVersion = httpVersion;
        this.paras = paras;
        this.uri = uri;
        this.formData = new FormData();
    }
    public FormDataBuilder  addFormField(String name, String value) {
        this.formData.putFiled(name,value);
        return this;
    }
    public FormDataBuilder addFileField(String name, byte[] bytes, String fileName, FileContentType fileContentType, boolean isText) {
        FileFiled fileFiled = new FileFiled(bytes,name, fileName, null, FileContentType.getType(fileContentType), isText);
        this.formData.putFileFiled(name,fileFiled);
        return this;
    }
    public FormDataBuilder addFileField(String name, File file, FileContentType fileContentType, boolean isText) {
        FileFiled fileFiled = new FileFiled(null,name, file.getName(), file, FileContentType.getType(fileContentType), isText);
        this.formData.putFileFiled(name,fileFiled);
        return this;
    }
    public FormDataBuilder addFileField(String name, Path path, FileContentType fileContentType, boolean isText) {
        if (!Files.isRegularFile(path)) {
            throw new IllegalStateException("File is not exist.");
        } else {
            File file = path.toFile();
            return addFileField(name,file,fileContentType,isText);
        }
    }

    public FormDataBuilder addFileField(String name, String pathS, FileContentType fileContentType, boolean isText) {
        Path path = Paths.get(pathS).toAbsolutePath().normalize();
        return addFileField(name,path,fileContentType,isText);
    }
    public HttpRequest build(){
        HttpRequest httpRequest = new HttpRequest(httpHeaders,httpVersion,httpMethod,uri);
        httpRequest.setParameters(paras);
        httpRequest.setFormData(formData);
        return httpRequest;
    }
}
